/*
 *所有关于Bas_Plant类的业务代码应在此处编写
 *可使用repository.调用常用方法，获取EF/Dapper等信息
 *如果需要事务请使用repository.DbContextBeginTransaction
 *也可使用DBServerProvider.手动获取数据库相关信息
 *用户信息、权限、角色等使用UserContext.Current操作
 *Bas_PlantService对增、删、改查、导入、导出、审核业务代码扩展参照ServiceFunFilter
 */

using DGZImp.Core.Utilities;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

namespace DGZImp.BasProject.Services
{
    public partial class Bas_PlantService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IBas_PlantRepository _repository;//访问数据库
        private readonly WebResponseContent _webResponse = new();

        [ActivatorUtilitiesConstructor]
        public Bas_PlantService(
            IBas_PlantRepository dbRepository,
            IHttpContextAccessor httpContextAccessor
            )
        : base(dbRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            _repository = dbRepository;
            //多租户会用到这init代码，其他情况可以不用
            //base.Init(dbRepository);
        }

        public override PageGridData<Bas_Plant> GetPageData(PageDataOptions options)
        {
            QueryRelativeExpression = (ISugarQueryable<Bas_Plant> queryable) =>
            {
                queryable.Includes(x => x.Company);
                return queryable;
            };
            return base.GetPageData(options);
        }

        public override WebResponseContent Add(SaveModel saveDataModel)
        {
            // 添加时候校验
            AddOnExecuting = (data, _) =>
            {
                return _repository.Exists(a =>
                    a.PlantCode == data.PlantCode && a.IsValid == 1) ? _webResponse.Error($"存在相同编号:\"{data.PlantCode}\"") : _webResponse.OK();
            };
            return base.Add(saveDataModel);
        }

        public override WebResponseContent Update(SaveModel saveDataModel)
        {
            // 修改时校验
            UpdateOnExecuting = (data, _, _, _) =>
            {
                return _repository.Exists(a =>
                    a.PlantCode == data.PlantCode && a.PlantId != data.PlantId && a.IsValid == 1) ? _webResponse.Error($"存在相同编号:\"{data.PlantCode}\"") : _webResponse.OK();
            };
            return base.Update(saveDataModel);
        }
    }
}
